package com.pitaya.winwine.service;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.pitaya.framework.common.ErrorInfo;
import com.pitaya.winwine.domain.User;
import com.pitaya.winwine.domain.Vintry;
import com.pitaya.winwine.domain.VintryLog;
import com.pitaya.winwine.domain.Wine;
import com.pitaya.winwine.repository.VintryRepository;
import com.pitaya.winwine.repository.WineRepository;
import com.pitaya.winwine.repository.spec.WineSpec;

@Service
@SuppressWarnings("deprecation")
public class VintryService {
	
	private static final Log log = LogFactory.getLog(VintryService.class);
	
	@Autowired
	private VintryRepository vintryRepository;
	
	@Autowired
	private WineRepository wineRepository;
	
	@Autowired
	private WineService wineService;

	@Transactional
	public Vintry create(Vintry vintry, @RequestParam("pic") MultipartFile file) {
		//判断是否需要创建红酒实体
		if(vintry.getWine().getId() == null) {
			//判断创建红酒是否存在
			Wine existWine = wineRepository.findOne(WineSpec.findExist(vintry.getWine()));
			if(existWine == null) {
				Wine wine = vintry.getWine();
				wine.setCreator(vintry.getUser());
				wine.setCreateTime(new Date());
				wine = wineService.createWine(wine, file);
				if(wine.getErrorInfo() != null) {
					return vintry;
				}
			}else {
				vintry.setErrorInfo(ErrorInfo.ISEXIST_WINE);
				vintry.setWine(existWine);
				return vintry;
			}
		}
		//判断将要创建酒管家是否存在
		Vintry existVintry = vintryRepository.findByUserIdAndWineId(vintry.getUser().getId(), vintry.getWine().getId());
		if(existVintry == null) {
			Wine wine = wineRepository.findOne(vintry.getWine().getId());
			Calendar calendar = Calendar.getInstance();
			calendar.set(wine.getVintage() + vintry.getDrinkingRange(), 0, 1, 0, 0, 0);
			vintry.setDrinkingPeriod(calendar.getTime());
			vintry.setEditTime(new Date());
			vintry.setTotal(0);
			return vintryRepository.save(vintry);
		}else {
			existVintry.setErrorInfo(ErrorInfo.ISEXIST_VINTRY);
			return existVintry;
		}
	}
	
	@Transactional
	public Vintry update(Vintry vintry) {
		Vintry v = vintryRepository.findOne(vintry.getId());
		if(vintry.getDrinkingRange() != null) {
			v.setDrinkingRange(vintry.getDrinkingRange());
			Calendar calendar = Calendar.getInstance();
			calendar.set(v.getWine().getVintage() + vintry.getDrinkingRange(), 0, 1, 0, 0, 0);
			v.setDrinkingPeriod(calendar.getTime());
		}
		if(vintry.getPrice() != null) v.setPrice(vintry.getPrice());
		if(vintry.getMarketPrice() != null) v.setMarketPrice(vintry.getMarketPrice());
		if(vintry.getRemark() != null) v.setRemark(vintry.getRemark());
		if(vintry.getTotal() != null) v.setTotal(vintry.getTotal());
		return vintryRepository.save(v);
	}
	
	public boolean export(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("application/vnd.ms-excel");
	    
	    Calendar calendar = Calendar.getInstance();
	    String date = new SimpleDateFormat("yyyy年MM月dd日").format(calendar.getTime());
	    StringBuilder sb = new StringBuilder();
	    sb.append("酒窖（柜）库存表_").append(date).append(".xls");
	    String fileName = "export";
	    try {
	    	fileName = URLEncoder.encode(sb.toString(), "UTF-8");
	    }catch (UnsupportedEncodingException e) {
	      log.error(e.getMessage());
	    }
	    response.setHeader("content-disposition", "attachment;filename=" + fileName);
	    
	    HSSFWorkbook workbook = new HSSFWorkbook();
	    HSSFSheet sheet = workbook.createSheet();
	    sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 4));
	    HSSFRow row = sheet.createRow(0);
	    HSSFCell cell = row.createCell(0);
	    StringBuilder title = new StringBuilder();
	    title.append(date).append("酒窖/酒柜库存表");
	    HSSFCellStyle titleStyle = workbook.createCellStyle();
	    titleStyle.setAlignment((short)2);
	    titleStyle.setVerticalAlignment((short)1);
	    cell.setCellValue(title.toString());
	    cell.setCellStyle(titleStyle);
	    row = sheet.createRow(2);
	    String[] columnName = { "红酒名称", "年份", "容量", "数量", "适饮期" };
	    for (int i = 0; i < columnName.length; i++) {
	    	cell = row.createCell(i);
	    	cell.setCellValue(columnName[i]);
	    }
	    int userId = ((User)session.getAttribute("user")).getId().intValue();
	    List<Vintry> list = vintryRepository.findByUserIdAndTotalGreaterThanOrderByEditTimeDesc(userId, 0);
	    for (int i = 0; i < list.size(); i++) {
	    	row = sheet.createRow(i + 3);
	    	StringBuilder name = new StringBuilder();
	    	name.append(list.get(i).getWine().getEnName()).append("/").append(list.get(i).getWine().getChName());
	    	row.createCell(0).setCellValue(name.toString());
	    	row.createCell(1).setCellValue(list.get(i).getWine().getVintage());
	    	row.createCell(2).setCellValue(list.get(i).getWine().getCapacity());
	    	row.createCell(3).setCellValue(list.get(i).getTotal());
	    	row.createCell(4).setCellValue(list.get(i).getDrinkingPeriod());
	    }
	    OutputStream outputStream = null;
	    try {
	    	outputStream = response.getOutputStream();
	    	workbook.write(outputStream);
	    }catch (IOException e) {
	    	log.error(e.getMessage());
	    	return false;
	    }finally {
	    	try {
	    		outputStream.flush();
	    		outputStream.close();
	    	}catch (IOException e) {
	    		log.error(e.getMessage());
	    		outputStream = null;
	    		return false;
	    	}
	    }
	    return true;
	}
	
	@Transactional
	public void addVintryLog(VintryLog vintryLog) {
		Vintry vintry = vintryRepository.findOne(vintryLog.getVintry().getId());
		if(vintryLog.getType() == VintryLog.STORE_IN) {
			vintry.setTotal(vintry.getTotal() + vintryLog.getNum());
		}else {
			vintry.setTotal(vintry.getTotal() - vintryLog.getNum());
		}
		vintryLog.setWine(vintry.getWine());
		Date date = new Date();
		vintry.setEditTime(date);
		vintryLog.setEditTime(date);
		vintry.addVintryLog(vintryLog);
	}
	
	/*public List<Vintry> getFoodList(Vintry vintry) {
		
	}*/
}
